package com.yy.finvideoplayer.floatwindow

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.FrameLayout
import kotlin.math.abs

/**
 * 浮窗容器
 * 拦截触摸移动事件，实现浮窗移动
 * @Description: FloatMoveView
 * @Author: yiw89
 * @CreateDate: 2025/9/1 14:11
 * @Version: 1.0
 */
class FloatMoveView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    FrameLayout(context, attrs, defStyleAttr) {
    private var touchSlop = 0

    private fun init(context: Context) {
        touchSlop = ViewConfiguration.get(context).scaledTouchSlop
    }

    private var isBeingDragged = false //是否触发拖曳
    private var mInitialMotionY = 0f
    private var mInitialMotionX = 0f

    //判断是否截取事件进行刷新
    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mInitialMotionY = ev.y
                mInitialMotionX = ev.x
                isBeingDragged = false
            }

            MotionEvent.ACTION_MOVE -> {
                val y = ev.y
                val x = ev.x
                isBeingDragged = abs((mInitialMotionY - y).toDouble()) > touchSlop ||
                        abs((mInitialMotionX - x).toDouble()) > touchSlop
                if (isBeingDragged) {
                    mInitialMotionY = ev.rawY
                    mInitialMotionX = ev.rawX
                }
            }

            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> isBeingDragged = false
        }
        return isBeingDragged
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (!isBeingDragged) return super.onTouchEvent(event)

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {}
            MotionEvent.ACTION_MOVE -> {
                val y = event.rawY
                val x = event.rawX
                moveListener!!.move((x - mInitialMotionX).toInt(), (y - mInitialMotionY).toInt())
            }

            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> moveListener!!.end()

        }
        return true
    }

    fun setRount(r: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            this.outlineProvider = TextureVideoViewOutlineProvider(r.toFloat())
            this.clipToOutline = true
        }
        //        GradientDrawable gradientDrawable = new GradientDrawable();
//        gradientDrawable.setCornerRadius(r);
//        setBackgroundDrawable(gradientDrawable);
    }

    interface MoveListener {
        fun move(x: Int, y: Int)

        fun end()
    }

    fun setMoveListener(moveListener: MoveListener?) {
        this.moveListener = moveListener
    }

    private var moveListener: MoveListener? = null

    init {
        init(context)
    }
}